package com.atguigu.guli.service.oss.service.Impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.atguigu.guli.service.oss.config.OssProperties;
import com.atguigu.guli.service.oss.service.FileService;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * ClassName: FileServiceImpl <br/>
 * Description: <br/>
 *
 * @author ZMR<br />
 * date: 2020/12/19 22:26<br/>
 * @since JDK 1.11
 */
@Service
public class FileServiceImpl implements FileService {
    @Autowired
    OssProperties ossProperties;

    String scheme;
    String endpoint;
    String keyId;
    String keySecret;
    String bucketName;

    @PostConstruct
    public void init() {
        scheme = ossProperties.getScheme();
        System.out.println(scheme);
        endpoint = ossProperties.getEndpoint();
        System.out.println(endpoint);
        keyId = ossProperties.getAccessKeyId();
        System.out.println(keyId);
        keySecret = ossProperties.getAccessKeySecret();
        System.out.println(keySecret);
        bucketName = ossProperties.getBucketName();
    }

    @Override
    public String uploadFile(MultipartFile multipartFile, String module) {
        OSS ossClient = new OSSClientBuilder().build(scheme + endpoint, keyId, keySecret);
        InputStream inputStream = null;
        try {
            inputStream = multipartFile.getInputStream();
//            生成文件名称
            String filename = multipartFile.getOriginalFilename();
//        截取文件后缀
            String suffix = filename.substring(filename.lastIndexOf("."));
            filename = UUID.randomUUID().toString().replace("-", "") + suffix;
            String dirs = new DateTime().toString("/yyyy/MM/dd/");
            filename = module + dirs + filename;
            System.out.println(filename);
            System.out.println(bucketName);
            ossClient.putObject(bucketName, filename, inputStream);
            ossClient.shutdown();
            //上传图片成功后，应该获取图片的地址(和新增的讲师绑定存到数据库中)
            //http://sh200821-gulionline.oss-cn-shanghai.aliyuncs.com/avatar/16.jpg
            //图片地址的构成： 协议+bucketName+ . + Endpoint+ / + 文件路径+文件名
            String path = scheme + bucketName + "." + endpoint + "/" + filename;
            return path;
        } catch (IOException e) {
            throw new RuntimeException();
        }

    }
}
